<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片式图 -->
    <el-card>
      <el-alert title="注意：只允许为第三级分类设置相关参数" type="warning" show-icon :closable='false'>
      </el-alert>

      <!-- 级联选择器 -->
      <div class="block" style="margin-top: 20px;">
        <span class="demonstration">选择商品分类：</span>
        <el-cascader v-model="selectCateKeys" :options="cateList" :props="cateProps" @change="handleChange">
        </el-cascader>
      </div>

      <!-- 标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态属性" name="many">
          <el-button size='mini' :disabled='isBtnDisabled' type="primary" @click='addDialogVisible=true'>添加参数
          </el-button>
          <!-- 动态参数表格 -->
          <el-table :data='manyTableData' border stripe>
            <el-table-column type='expand'>
              <template slot-scope='scope'>
                <el-tag type="success" closable v-for='(str,index) in scope.row.attr_vals' :key='index'
                  style="margin-right: 10px;" @close="handleClose(index,scope.row)">
                  {{str}}
                </el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                  ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type='index'></el-table-column>
            <el-table-column label='参数名称' prop='attr_name'></el-table-column>
            <el-table-column label='操作'>
              <template slot-scope='scope'>
                <el-button type="primary" size='mini' con="el-icon-edit" @click='showEditDialog(scope.row.attr_id)'>编辑
                </el-button>
                <el-button size='mini' type='danger' con="el-icon-delete" @click='showDeleteDialog(scope.row.attr_id)'>
                  删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button size='mini' :disabled='isBtnDisabled' type="primary" @click='addDialogVisible=true'>添加属性
          </el-button>
          <!-- 静态属性表格 -->
          <el-table :data='onlyTableData' border stripe>
            <el-table-column type='expand'></el-table-column>
            <el-table-column type='index'></el-table-column>
            <el-table-column label='属性名称' prop='attr_name'></el-table-column>
            <el-table-column label='操作'>
              <template slot-scope='scope'>
                <el-button type="primary" size='mini' con="el-icon-edit" @click='showEditDialog(scope.row.attr_id)'>编辑
                </el-button>
                <el-button size='mini' type='danger' con="el-icon-delete" @click='showDeleteDialog(scope.row.attr_id)'>
                  删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!--  添加参数对话框-->
    <el-dialog :title="'添加' + titleText" :visible.sync="addDialogVisible" width="50%" @close='addDialogClosed'>
      <span>
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" class="demo-ruleForm">
          <el-form-item :label="titleText" prop="addForm.attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click=" editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!--  修改参数对话框-->
    <el-dialog :title="'修改' + titleText" :visible.sync="editDialogVisible" width="50%" @close='editDialogClosed'>
      <span>
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" class="demo-ruleForm">
          <el-form-item :label="titleText" prop="editForm.attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click=" editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script scoped>
  export default {
    created() {
      this.getCateList()
    },
    data() {
      return {
        inputValue: '',
        inputVisible: false,
        // 添加参数表单数据对象
        addForm: {
          attr_name: ''
        },
        // 添加表单的验证规则对象
        addFormRules: {
          attr_name: [{
            required: true,
            message: '请输入参数名称',
            trigger: 'blur'
          }]
        },
        // 控制添加对话框的显示与隐藏
        addDialogVisible: false,
        // 默认标签页为第一个
        activeName: 'many',
        // 级联选择框绑定的数组
        selectCateKeys: [],
        // 级联选择框配置对象
        cateProps: {
          expandTrigger: 'hover',
          value: 'cat_id',
          label: 'cat_name',
          children: 'children'
        },
        // 商品分类列表
        cateList: [],
        manyTableData: [],
        onlyTableData: [],
        editDialogVisible: false,
        editForm: {},
        editFormRules: {
          attr_name: [{
            required: true,
            message: '请输入参数名称',
            trigger: 'blur'
          }]
        }
      }
    },
    methods: {
      handleClose(i, row) {
        row.attr_vals.splice(i, 1)
        this.saveAttrVals(row)
      },
      async saveAttrVals(row) {
        const {
          data: res
        } = await this.$axios.put(
          `categories/${this.cateId}/attributes/${row.attr_id}`, {
            attr_name: row.attr_name,
            attr_sel: row.attr_sel,
            attr_vals: row.attr_vals.join(' ')
          }
        )
        if (res.meta.status !== 200) return this.$message.error('修改参数项失败')
        this.$message.success('修改参数项成功')
      },
      showInput(obj) {
        obj.inputVisible = true
        this.$nextTick(_ => {
          return this.$refs.saveTagInput.$refs.input.focus()
        })
      },
      async handleInputConfirm(row) {
        if (row.inputValue.trim().length === 0) {
          row.inputValue = ''
          row.inputVisible = false
          return
        }
        row.attr_vals.push(row.inputValue.trim())
        row.inputValue = ''
        row.inputVisible = false
        this.saveAttrVals(row)
      },
      async showDeleteDialog(id) {
        const confirmResult = await this.$confirm('此操作将永久删除该数据, 是否继续?', '提示删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if (confirmResult !== 'confirm') return this.$message.info('已取消删除')
        const {
          data: res
        } = await this.$axios.delete(`categories/${this.cateId}/attributes/${id}`)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        this.getCateList()
      },
      editParams() {
        this.$refs.editFormRef.validate(async valid => {
          if (!valid) return
          const {
            data: res
          } = await this.$axios.put(
            `categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
              attr_name: this.editForm.attr_name,
              attr_sel: this.activeName
            }
          )
          if (res.meta.status !== 200) return this.$message.error('编辑失败')
          this.getCateList()
          this.editDialogVisible = false
        })
      },
      editDialogClosed() {
        this.$refs.editFormRef.resetFields()
      },
      async showEditDialog(id) {
        const {
          data: res
        } = await this.$axios({
          url: `categories/${this.cateId}/attributes/${id}`,
          params: {
            attr_sel: this.activeName
          }
        })
        if (res.meta.status !== 200) return this.$message.error('获取参数信息失败')
        this.editForm = res.data
        this.editDialogVisible = true
      },
      // 点击按钮添加参数
      addParams() {
        this.$refs.addFormRef.validate(async valid => {
          if (!valid) return
          const {
            data: res
          } = await this.$axios({
            url: `categories/${this.cateId}/attributes`,
            method: 'POST',
            data: {
              attr_name: this.addForm.attr_name,
              attr_sel: this.activeName
            }
          })
          if (res.meta.status !== 201) return this.$message.error('添加参数失败!')
          this.$message.success('添加参数成功!')
          this.addDialogVisible = false
          this.getCateList()
        })
      },
      addDialogClosed() {
        this.$refs.addFormRef.resetFields()
      },
      // tab页签事件处理函数
      handleTabClick() {
        this.getParamsData()
      },
      handleChange() {
        this.getParamsData()
      },
      // 获取所有商品分类
      async getCateList() {
        const {
          data: res
        } = await this.$axios({
          url: 'categories'
        })
        if (res.meta.status !== 200) return this.$message.error('获取商品分类失败!')
        this.cateList = res.data
      },
      // 获取参数列表数据
      async getParamsData() {
        // 证明选中的不是三级分类
        if (this.selectCateKeys.length !== 3) {
          this.selectCateKeys = []
        }
        // 证明选中的是三级分类
        const {
          data: res
        } = await this.$axios({
          url: `categories/${this.cateId}/attributes`,
          params: {
            sel: this.activeName
          }
        })
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          item.inputValue = ''
          item.inputVisible = false
        })
        if (res.meta.status !== 200) return this.$message.error('获取参数失败!')
        if (this.activeName === 'many') {
          this.manyTableData = res.data
        } else {
          this.onlyTableData = res.data
        }
      }
    },
    computed: {
      isBtnDisabled() {
        if (this.selectCateKeys.length !== 3) return true
        return false
      },
      cateId() {
        if (this.selectCateKeys.length === 3) return this.selectCateKeys[2]
        return null
      },
      // 动态计算标题文本
      titleText() {
        if (this.activeName === 'many') {
          return '动态参数'
        }
        return '静态属性'
      }
    }
  }

</script>

<style scoped>
  .input-new-tag {
    width: 120px;
  }

</style>
